package com.sl.biz.modular.ai.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.sl.core.utils.JsonUtil;
import com.volcengine.ark.runtime.model.completion.chat.ChatCompletionContentPart;
import com.volcengine.ark.runtime.model.completion.chat.ChatCompletionRequest;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessage;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessageRole;
import com.volcengine.ark.runtime.service.ArkService;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import okhttp3.ConnectionPool;
import okhttp3.Dispatcher;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.*;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/ai/biz")
@RequiredArgsConstructor
public class AIBizController {
    static String baseUrl = "https://ark.cn-beijing.volces.com/api/v3";
    static ConnectionPool connectionPool = new ConnectionPool(5, 5, TimeUnit.SECONDS);
    static Dispatcher dispatcher = new Dispatcher();
    static ArkService service;

    @PostMapping("/send")
    public List<String> send(@RequestBody Map<String, Object> params) {
        service = ArkService.builder().dispatcher(dispatcher).connectionPool(connectionPool).baseUrl(baseUrl).apiKey("71f4285c-af6b-48f2-a02c-bffa4aa96fec").build();

        String s = MapUtil.getStr(params, "image");
        String wrapperStr = MapUtil.getStr(params, "wrapperStr");
        if (1 == 1) {
            List<String> strings = null;
            try {
                strings = sendTotongyi(wrapperStr, s);
            } catch (Exception e) {
                e.printStackTrace();
                ;
            }
            if (CollUtil.isNotEmpty(strings)) {
                return strings;
            }
        }
        if (1 == 2) {
            List<String> strings = null;
            try {
                sendXinghuo(wrapperStr, s);
            } catch (Exception e) {
                e.printStackTrace();
                ;
            }
            if (CollUtil.isNotEmpty(strings)) {
                return strings;
            }
        }

        System.out.println("----- image input -----");
        final List messages = new ArrayList<>();
        final List multiParts = new ArrayList<>();
        multiParts.add(ChatCompletionContentPart.builder().type("image_url").imageUrl(
                new ChatCompletionContentPart.ChatCompletionContentPartImageURL(
                        s,
                        "high"
                )
        ).build());
        multiParts.add(ChatCompletionContentPart.builder().type("text").text(
                StrUtil.nullToDefault(wrapperStr, "请给图片中的人给出特征，再给图中的人周易来总结一下，必须总结")
        ).build());

        final ChatMessage userMessage = ChatMessage.builder().role(ChatMessageRole.USER)
                .multiContent(multiParts).build();
        messages.add(userMessage);

        ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
                // 指定您创建的方舟推理接入点 ID，此处已帮您修改为您的推理接入点 ID
                .model("doubao-1.5-vision-pro-250328")
                .messages(messages)
                .build();

        new AIBizController().lijieImage();
        List<String> result = Lists.newArrayList();
        service.createChatCompletion(chatCompletionRequest).getChoices().forEach(choice -> result.add(choice.getMessage().getContent().toString()));

        service.shutdownExecutor();
        return result;
    }

    public static List<String> sendXinghuo(String message, String imageUrl) {
        String ak = "wMdAzDdgdPYgosKVhsKa:lDQPkkeHPMbrYHpEAjuR";
        String jsonBody = "{\n" +
                "    \"header\": {\n" +
                "        \"app_id\": \"6ebf802c\",\n" +
                "        \"uid\": \"\"\n" +
                "    },\n" +
                "    \"parameter\": {\n" +
                "        \"chat\": {\n" +
                "            \"domain\": \"imagev3\",\n" +
                "            \"temperature\": 0.5,\n" +
                "            \"top_k\": 4,\n" +
                "            \"max_tokens\": 2028\n" +
                "        }\n" +
                "    },\n" +
                "    \"payload\": {\n" +
                "        \"message\": {\n" +
                "            \"text\": [\n" +
                "                {\n" +
                "                    \"role\": \"user\",\n" +
                "                    \"content\": \"" + imageUrl + "\",\n" +
                "                    \"content_type\": \"image\"\n" +
                "                },\n" +
                "                {\n" +
                "                    \"role\": \"user\",\n" +
                "                    \"content\": \"" + message + "\",\n" +
                "                    \"content_type\": \"text\"\n" +
                "                }\n" +
                "            ]\n" +
                "        }\n" +
                "    }\n" +
                "}";
        Map<Object, Object> map = JsonUtil.toMap(jsonBody, String.class, Object.class);
        map.put("model", "generalv3.5");
        HttpRequest httpRequest = new HttpRequest("https://spark-api-open.xf-yun.com/v1/chat/completions");
        httpRequest.setMethod(Method.POST);
        httpRequest.header("Content-Type", "application/json");
        httpRequest.header("Authorization", "Bearer " + ak);
        httpRequest.setConnectionTimeout(300000);
        httpRequest.setReadTimeout(300000);
        httpRequest.body(JsonUtil.toStr(map));
        String body = httpRequest.execute().body();
        System.out.println(body);
        return null;
    }

    @SneakyThrows
    public static List<String> sendTotongyi(String message, String imageUrl) {
        String ak = "sk-f469c26a2f3b4a1bbf8094a71957fc47";
        Long startTime = System.currentTimeMillis();
        byte[] bytes = HttpUtil.downloadBytes(imageUrl);
        System.out.println("下载文件耗时" + (System.currentTimeMillis() - startTime));
        String encode = Base64.encode(bytes);
        imageUrl = "data:image/jpeg;base64," + encode;
        // 2. 构造请求体;
        String jsonBody = "{\n" +
                "  \"model\": \"qwen-vl-max\",\n" +
                "  \"lang\":\"zh\",\"messages\": [\n" +
                "  {\"role\":\"system\",\n" +
                "  \"content\":[\n" +
                "    {\"type\": \"text\", \"text\": \"\"}]},\n" +
                "  {\n" +
                "    \"role\": \"user\",\n" +
                "    \"content\": [\n" +
                "      {\"type\": \"image_url\", \"image_url\": {\"url\": \"" + imageUrl + "\"}},\n" +
                "      {\"type\": \"text\", \"text\": \"" + message + "\"}\n" +
                "    ]\n" +
                "  }]\n" +
                "}";

        HttpRequest httpRequest = new HttpRequest("https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions");
        httpRequest.setMethod(Method.POST);
        httpRequest.header("Content-Type", "application/json");
        httpRequest.header("Authorization", "Bearer " + ak);
        httpRequest.setConnectionTimeout(300000);
        httpRequest.setReadTimeout(300000);
        httpRequest.body(jsonBody);
        String body = httpRequest.execute().body();
        System.out.println(body);
        // 解析到嵌套的数组
        Map<String, Object> map = JsonUtil.toMap(body);
        List choices = MapUtil.get(map, "choices", List.class);
        List<String> result = Lists.newArrayList();
        choices.forEach(v -> {
            Map<String, Object> mo = JsonUtil.toMap(v);
            String s1 = BeanUtil.getProperty(mo, "message.content");
            result.add(s1);
        });
        return result;
    }

    @SneakyThrows
    public void lijieImage() {
        String url = "https://visual.volcengineapi.com?Action=CVProcess&Version=2022-08-31";
        String ak = "5d555f74-2eed-4b70-b21d-3cf8c2ed9231";
        /// https://ark-project.tos-cn-beijing.volces.com/images/view.jpeg
        String jsonBody = "{\n" +
                "    \"req_key\": \"dressing_diffusion\",\n" +
                "    \"model\": {\n" +
                "        \"id\": \"1\",\n" +
                "        \"url\": \"https://ark-project.tos-cn-beijing.volces.com/images/view.jpeg\"\n" +
                "    },\n" +
                "    \"garment\": {\n" +
                "        \"id\": \"1\",\n" +
                "        \"data\": [\n" +
                "            {\n" +
                "                \"url\": \"https://ark-project.tos-cn-beijing.volces.com/images/view.jpeg\"\n" +
                "            }\n" +
                "        ]\n" +
                "    },\n" +
                "    \"return_url\": true,\n" +
                "    \"logo_info\": {\n" +
                "        \"add_logo\": false,\n" +
                "        \"position\": 0,\n" +
                "        \"language\": 0,\n" +
                "        \"logo_text_content\": \"这里是明水印内容\"\n" +
                "    }\n" +
                "}";
        HttpRequest httpRequest = new HttpRequest(url);
        httpRequest.setMethod(Method.POST);
        httpRequest.header("Content-Type", "application/json");
        httpRequest.header("Authorization", "Bearer " + ak);
        httpRequest.setConnectionTimeout(300000);
        httpRequest.setReadTimeout(300000);
        httpRequest.body(jsonBody);
        String body = httpRequest.execute().body();
        Map<Object, Object> map = JsonUtil.toMap(body, String.class, Object.class);
        Object property = BeanUtil.getProperty(map, "$.data.embedding");

        property = "data:image/jpeg;base64," + property;
        System.out.println(property);
        Base64.decodeToFile(property.toString(), new File("/Users/weixin/work/project/self/square-lake/square-lake-module/square-lake-biz/src/main/java/com/sl/biz/modular/ai/controller/c.jpeg"));
    }

    public static List<String> sendTozhipu(String message, String imageUrl) {
        String ak = "5289ce7bb5c94cff884c50aaa12dcd44.JMBFogNK39vOnER8";
        String json = "{\"messages\":[\n" +
                "       {\n" +
                "        \"role\": \"user\",\n" +
                "        \"content\": [\n" +
                "          {\n" +
                "            \"type\": \"text\",\n" +
                "            \"text\": \"" + message + "\"\n" +
                "          },\n" +
                "          {\n" +
                "            \"type\": \"image_url\",\n" +
                "            \"image_url\": {\n" +
                "                \"url\" : \"" + imageUrl + "\"\n" +
                "            }\n" +
                "          }\n" +
                "        ]\n" +
                "      }\n" +
                "    ]}";
        Map<Object, Object> map = JsonUtil.toMap(json, String.class, Object.class);
        map.put("model", "glm-4-plus");

        HttpRequest httpRequest = new HttpRequest("https://open.bigmodel.cn/api/paas/v4/chat/completions");
        httpRequest.setMethod(Method.POST);
        httpRequest.header("Content-Type", "application/json");
        httpRequest.header("Authorization", "Bearer " + ak);
        httpRequest.setConnectionTimeout(300000);
        httpRequest.setReadTimeout(300000);
        httpRequest.body(JsonUtil.toStr(map));
        String body = httpRequest.execute().body();
        System.out.println(body);
        return null;
    }

    public static BufferedImage convertFloatVectorToImage(Float[] vector, int width, int height) {
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                int index = y * width + x;
                float value = vector[index];

                // 将 float 值映射到 0 - 255 的范围，并进行范围检查
                int grayValue = (int) (value * 255);
                grayValue = Math.max(0, Math.min(255, grayValue));

                Color color = new Color(grayValue, grayValue, grayValue);
                image.setRGB(x, y, color.getRGB());

            }
        }

        return image;
    }

    public static void main(String[] args) {
//        GlobalHeaders.INSTANCE.header("Referer", "https://www.earthcam.com/usa/michigan/gaylord/snowman/?cam=snowman");
//
//        String s = HttpUtil.get("https://www.earthcam.com/api/ectv/player/playlist?r=playlist&a=fetch");
//        //w417875060
//        Map<Object, Object> map = JsonUtil.toMap(s, String.class, Object.class);
//        Object property = BeanUtil.getProperty(map, "$.data.playlist_trending.playlist_items");
//        System.out.println(property.toString());
//        if (property instanceof Collection cl) {
//            Object collect = cl.stream().filter(v -> {
//                if (v instanceof Map m) {
//                    String state = MapUtil.getStr(m, "state");
//                    return StrUtil.equalsAnyIgnoreCase("MI",state);
//                }
//                return false;
//            }).findFirst().orElse(null);
//            property = BeanUtil.getProperty(collect, "stream");
//        }
//        if(ObjectUtil.isNull(property)){
//            property = BeanUtil.getProperty(map, "$.data.playlist_trending.playlist_items[0].stream");
//        }
//        File tempFile = FileUtil.createTempFile();
//        String s3 = StrUtil.subPre(property.toString(), 109);
//        String s2 = s3+"Y3DeAT%2BjmWpkzrJsvxn";
//
//        URL url1 = URLUtil.url(((String) property).toLowerCase());
//        String query = url1.getQuery();
//        Map<String, List<String>> stringListMap = HttpUtil.decodeParams(query, Charset.defaultCharset());
//        GlobalHeaders.INSTANCE.header("Referer", "https://www.earthcam.com/");
//        https://videos-3.earthcam.com/fecnetwork/13706.flv/chunklist_w428050198.m3u8?t=z6nB2mvB7fVRwGP9d5q8HkQOt517mPZeS8kGxr9WE4yWEY3DeAT&td=202504300231
//
//        //z6nB2mvB7fVRwGP9d5q8HkQOt517mPZeS8kGxr9WE4yWEY3DeAT
//        HttpUtil.downloadFileFromUrl(property.toString(), tempFile, -1);
////            String fileUrl = "https://videos-3.earthcam.com/fecnetwork/4280.flv/playlist.m3u8?t=Z8SpBH92uYu3pHPoOMZ%2B9zmlj1I9el%2F0SgTs%2BxGjkms4942HDUzWzO%2FSnMBrgDMs&td=202504300136";
////            String savePath = "your_save_path.m3u8";
//
//        String s1 = FileUtil.readString(tempFile, Charset.defaultCharset());
//        List<String> split = StrUtil.split(s1, "chunklist");
//        System.out.println(s1);
//        List<String> t = stringListMap.get("t");
//        List<String> td = stringListMap.get("td");
//        String trunc = "chunklist" + CollUtil.get(split, 1);
//       trunc = URLUtil.decode(trunc);
//        String url = "https://videos-3.earthcam.com/fecnetwork/13706.flv/" + trunc;
//        System.out.println(url);
        String me = "今天是阳历2025-05-05 14:45:10，温度29度,天气晴.你是一个熟度麻衣相法,水镜神相,熟知周易，易经，八字命理，四柱预测，紫微斗数，排大运，六爻预测，风水命理，十二时辰(吉凶)推断法,相术，梅花易数，奇门遁甲，太乙神数，卜筮,易卦，梅花易数,占梦，穷通宝典，三命通会，滴天髓，渊海子平，千里命稿，协纪辨方书，果老星宗，子平真栓，神峰通考，铁板神数，占星术，五行术，堪舆术，谶语，拆字，六壬，，铁版神数，塔罗牌，哲学思考等的国家民族文化研究者,你非常尊重并热爱科学，你需要对传统算命相学等进行研究，并形成报告，并严格按照八字命理的理论和步骤来分析.请根据图中的人或者物从细节上总结出各个特征，再结合今天的日期天气时代，看一下我的八字和大运流年，同时测算一下今年和今天的事业、情感、生活等方面的运势，根据以上内容并给出建议，佩戴什么物品可以改善、提高运势,详细解释每一个指标，字数不应该少于800字";

        List<String> split = StrUtil.split(me, "你是一个熟度麻衣相法");
        String jbxx = CollUtil.get(split, 0);
        List<String> jbxxList = new ArrayList();
        if (StrUtil.isNotBlank(jbxx)) {
            jbxxList = StrUtil.split(jbxx, ",");

        }
        String gd = CollUtil.get(split, 1);

        String str1 = "1. 用户输入信息\n" +
                "基础信息：\n" +
                "姓名：{userName}\n" +
                "手机号：{phone}\n" +
                "出生日期：{birthday}\n" +
                "性别：{gender}\n" +
                "出生体重：{birthwait}\n" +
                "当前时间：{nowDay}\n" +
                "天气：{tempture}\n" +
                "其他需求：\n" +
                "你需模拟精通麻衣相法、周易、八字、紫微斗数、奇门遁甲等传统文化的专家角色。\n" +
                "回答需基于图片特征（如五官比例、气色、表情等）进行分析，避免脱离图像主观臆断。\n" +
                "2. 分析维度要求\n" +
                "请从以下10个维度展开分析，每部分需结合图片特征与传统文化理论：\n" +
                "\n" +
                "八字命理：年柱、月柱、日柱、时柱及五行平衡。\n" +
                "大运流年：2025年乙巳大运与当前流年吉凶预测。\n" +
                "麻衣相法：五岳三停、五官气色、面部纹理等。\n" +
                "紫微斗数：命宫、财帛宫、夫妻宫星曜配置。\n" +
                "十二时辰：当前辰时吉凶与今日宜忌事项。\n" +
                "风水环境：根据出生时间推断家居风水布局建议。\n" +
                "生活建议：饮食、穿搭、佩戴物品（需结合五行属性）。\n" +
                "情感婚姻：配偶性格、婚姻吉凶与改善建议。\n" +
                "事业财运：职业发展方向、投资理财注意事项。\n" +
                "健康预警：根据出生时间与天气，提示潜在健康风险。\n" +
                "3. 风险提示与合规要求\n" +
                "科学态度：需注明“命理分析仅作娱乐参考，不构成医疗或投资建议”。\n" +
                "图像关联性：若图片模糊或特征不明显，需提示“因图像质量限制，以下分析基于常规理论推演”。\n" +
                "文化融合：避免涉及敏感话题（如政治、宗教），保持传统文化与现代科学的平衡。\n" +
                "4. 输出格式要求\n" +
                "结构清晰：按上述10个维度分点论述，每部分标注标题（如“一、八字命理分析”）。\n" +
                "语言风格：专业性与通俗性结合，避免晦涩术语堆砌。\n" +
                "字数要求：总字数≥800字，每维度约200-400字。";
        Map<String, Object> result = new HashMap<>();
        result.put("userName", StrUtil.replace(CollUtil.get(jbxxList, 0), "我的名字叫", ""));
        result.put("phone", StrUtil.replace(CollUtil.get(jbxxList, 1), "我的手机号是", ""));
        result.put("birthday", StrUtil.replace(CollUtil.get(jbxxList, 2), "我的出生日期是", "") + " " + StrUtil.replace(CollUtil.get(jbxxList, 3), "我的出生时间是", ""));
        result.put("gender", StrUtil.nullToDefault(StrUtil.replace(CollUtil.get(jbxxList, 4), "我的性别是", ""), "未知"));
        result.put("birthwait", StrUtil.replace(CollUtil.get(jbxxList, 5), "我出生时的体重时、是", "") + StrUtil.replace(CollUtil.get(jbxxList, 6), "我的其他信息是", ""));

        var sv = CollUtil.get(jbxxList, 7);
        List<String> svList = StrUtil.split(sv, "，");

        result.put("nowDay", StrUtil.nullToDefault(StrUtil.replace(CollUtil.get(svList, 0), "今天是阳历", ""), ""));
        result.put("tempture", StrUtil.nullToDefault(StrUtil.replace(CollUtil.get(jbxxList, 8), "天气", ""), ""));
        str1 = StrUtil.format(str1, result);
        str1 = StrUtil.replace(str1, "\n", "");
        str1 = StrUtil.replace(str1, "null", "");

        Map<String, Object> pa = new HashMap<>();
        pa.put("image", "https://www.50ak.com/api/dev/file/download?id=1920049141320564738");
        var str = "请基于给的图片生成一张唐代风格的人物,确保你给的地址能访问";
        Map<String, Object> map = new HashMap<>();
        map.put("userName", "");
        map.put("phone", "");
        map.put("birthday", "");
        map.put("gender", "");
        map.put("birthwait", "");

        map.put("nowDay", "");
        map.put("tempture", "");
        str = StrUtil.format(str, map);
        str = StrUtil.replace(str, "\n", "");
        pa.put("wrapperStr", str);
//        new AIBizController().lijieImage();
//            List<String> strings1 = sendTozhipu(MapUtil.getStr(pa, "image"), MapUtil.getStr(pa, "message"));
        List<String> strings = new AIBizController().send(pa);
        System.out.println(strings);
    }

    @PostMapping("/getMessage")
    public String getMessage(@RequestBody Map<String, Object> params) {
        return MapUtil.getStr(params, "message");
    }

    @SneakyThrows
    @PostMapping("/sendToImages")
    public String sendToImages(@RequestBody Map<String, Object> params) {

        String s = MapUtil.getStr(params, "image");
        String dynasty = MapUtil.getStr(params, "dynasty");
        // 火山官网密钥信息, 注意sk结尾有==
        String AccessKeyID = "AKLTYmEzMmEwNTdjMWIzNDEyMWFhNjg0MmFkMjUyZWVmMTk";
        String SecretAccessKey = "T0RsaU1UVXpZelZrWVRKa05HTXpPRGhpT0ROaU1qaG1ZVGd5WWpjNE1qTQ==";
        // 请求域名
        String endpoint = "visual.volcengineapi.com";
        String path = "/"; // 路径，不包含 Query// 请求接口信息
        String service = "cv";
        String region = "cn-north-1";
        String schema = "https";
        Sign sign = new Sign(region, service, schema, endpoint, path, AccessKeyID, SecretAccessKey);
        // 参考接口文档Query参数
        String action = "CVProcess";
        String version = "2022-08-31";
        Date date = new Date();
        // 参考接口文档Body参数
        JSONObject req = new JSONObject();
        req.put("req_key", "high_aes_general_v30l_zt2i");
        ArrayList<String> imageUrls = new ArrayList<String>();
        imageUrls.add(s);
        req.put("image_urls", imageUrls);
        req.put("prompt", "帮穿越到" + dynasty);
        return sign.doRequest("POST", new HashMap(), req.toJSONString().getBytes(), date, action, version);
    }
}
